<template>
  <div class="app-container">
    <my-tree-selector-query
      title="部署区域"
      :current-node-key="this.queryParams.regionId"
      :default-expanded-keys="[provinceIdConfig]"
      :options="regionDataOptions"
      :treeProps="{ children: 'children',label: 'name'}"
      @click-node="handleNodeClick"
    />

    <div class="right-wrap">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="设备ID" prop="deviceId">
          <el-input
            v-model="queryParams.deviceId"
            placeholder="请输入设备ID"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="部署名称" prop="deploymentName">
          <el-input
            v-model="queryParams.deploymentName"
            placeholder="请输入设备部署名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="部署分组" prop="groupId">
          <treeselect
            v-model="queryParams.groupId"
            :options="filterGroupOptions"
            :normalizer="treeNormalizer"
            :show-count="true"
            placeholder="选择分组"
            noOptionsText="暂无选项"
            noResultsText="没有匹配的搜索结果"
          />
        </el-form-item>

        <el-form-item label="运维人员" prop="operationUserName">
          <el-select
            size="small"
            v-model="queryParams.operationUserName"
            placeholder="请选择运维负责人姓名"
            clearable
            filterable
            class="custom-input-width"
          >
            <el-option
              v-for="item in operationUserOptions"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态" prop="deviceStatus">
          <el-select
            v-model="queryParams.deviceStatus"
            placeholder="请选择设备状态"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in dict.type.device_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="设备型号" prop="deviceName">
          <el-input
            v-model="queryParams.deviceName"
            placeholder="请输入设备型号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="默认网点" prop="branchCode">
           <treeselect
                v-model="queryParams.branchCode"
                :options="branchDataOptions"
                :normalizer="branchNormalizer"
                placeholder="选择设备部署默认网点"
                style="width: 240px"
                noOptionsText="暂无选项"
                noResultsText="没有匹配的搜索结果"
              />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['device:placeManager:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate(ids[0])"
            v-hasPermi="['device:placeManager:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['device:placeManager:remove']"
          >删除
          </el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['device:placeManager:export']"
          >导出
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table
        ref="tables"
        v-loading="loading"
        :data="list"
        @selection-change="handleSelectionChange"
        tooltip-effect="light"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" v-if="showSelection"/>
        <el-table-column label="部署名称" align="center" prop="deploymentName" show-overflow-tooltip/>
        <el-table-column label="设备ID" align="center" prop="deviceId" width="190"/>
        <el-table-column label="设备型号" align="center" prop="deviceName" show-overflow-tooltip>
          <div slot-scope="scope" :class="[{pointer:hasDeviceInfoPermission}]"
               @click="navToDeviceInfo(scope.row.deviceCode)">
            {{ scope.row.deviceName }}
          </div>
        </el-table-column>
        <el-table-column label="部署区域" align="center">
          <template slot-scope="scope">
            {{ scope.row.ancestorsName }}
            <!--            {{ scope.row.deploymentAddress }}-->
          </template>
        </el-table-column>
        <el-table-column label="部署分组" align="center" prop="groupName" />
        <el-table-column label="设备状态" align="center" width="100">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.device_status"
              :value="scope.row.deviceStatus"
              @click.native="navToDeviceStatusLog(scope.row.deviceStatus,scope.row.deviceId)"
              :class="[{pointer:hasFaultPermission || hasStatusPermission}]"
            />
          </template>
        </el-table-column>
        <el-table-column label="运维人员" align="center" prop="operationUserName" width="120">
          <div slot-scope="scope" @click="navToOperation(scope.row.operationUserName)"
               :class="[{pointer:hasOperationUserPermission}]">
            {{ scope.row.operationUserName }}
          </div>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row,scope.index)"
              v-hasPermi="['device:placeManager:query']"
            >详细
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row,'table')"
              v-hasPermi="['device:placeManager:edit']"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['device:placeManager:remove']"
            >删除
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-cpu"
              @click="handleViewDeviceModules(scope.row,scope.index)"
              v-hasPermi="['device:model:listByDeviceInnerCode']"
            >查看设备模块
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 设备部署详细信息 -->
    <el-dialog
      title="设备部署详细信息"
      :visible.sync="deviceDetailDialogVisible"
      width="800px"
    >
      <device-detail-info
        v-loading="deviceDetailDialogLoading"
        :deviceDetailInfoForm="deviceDetailInfoForm"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="deviceDetailDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改设备部署信息 -->
    <el-dialog
      :title="editDeviceInfoDialogTitle"
      :visible.sync="editDeviceDialogVisible"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
      ref="editDeviceInfoDialog"
    >
      <el-form
        ref="editDeviceInfoForm"
        :model="editDeviceInfoDialogForm"
        :rules="editDeviceInfoDialogRules"
        label-width="110px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="设备ID" prop="deviceId">
              <el-input
                v-model="editDeviceInfoDialogForm.deviceId"
                placeholder="请输入设备ID"
                :disabled="Boolean(editDeviceInfoDialogForm.id)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="部署名称" prop="deploymentName">
              <el-input v-model="editDeviceInfoDialogForm.deploymentName" placeholder="请输入设备部署名称"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="设备型号" prop="deviceCode">
              <el-select
                v-model="editDeviceInfoDialogForm.deviceCode"
                clearable
                filterable
                placeholder="请选择设备型号"
                class="custom-input-width"
              >
                <el-option
                  v-for="(item,index) in deviceTypeAndBomCodeOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="设备序列号" prop="deviceSn">
              <el-input v-model="editDeviceInfoDialogForm.deviceSn" placeholder="请输入设备序列号"/>
            </el-form-item>
            <el-form-item label="设备部署区域" prop="ancestors">
              <el-cascader
                style="width: 100%;"
                filterable
                clearable
                v-model="editDeviceInfoDialogForm.ancestors"
                ref="cascader"
                placeholder="请选择设备部署区域"
                :props="elCascaderProps"
                :options="pageRegionDataOptions"
                @change="(arr)=>getRegionGroup(arr[arr.length-1],'addDeviceGroupOptions')"
              />
            </el-form-item>
            <el-form-item label="设备部署分组" prop="groupId">
              <treeselect
                v-model="editDeviceInfoDialogForm.groupId"
                :options="addDeviceGroupOptions"
                :normalizer="treeNormalizer"
                placeholder="选择设备部署分组"
                class="custom-input-width"
                @select="handleGroupChange"
                noOptionsText="暂无选项"
                noResultsText="没有匹配的搜索结果"
              />
            </el-form-item>

            <el-form-item label="默认网点" prop="branchCode">
              <treeselect
                v-model="editDeviceInfoDialogForm.branchCode"
                :options="branchDataOptions"
                :normalizer="branchNormalizer"
                placeholder="选择设备部署默认网点"
                class="custom-input-width"
                noOptionsText="暂无选项"
                noResultsText="没有匹配的搜索结果"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="设备生产日期" prop="productionDate">
              <el-date-picker
                v-model="editDeviceInfoDialogForm.productionDate"
                type="date"
                placeholder="请选择设备生产日期"
                value-format="yyyy-MM-dd"
                class="custom-input-width"
              >
              </el-date-picker>
            </el-form-item>

            <!--    <el-form-item label="粤自助设备编号" prop="yzzDeviceCode">
                  <el-input v-model="editDeviceInfoDialogForm.yzzDeviceCode" placeholder="请输入粤自助设备编号"/>
                </el-form-item>

                <el-form-item label="粤自助注册码" prop="yzzSerialNumber">
                  <el-input v-model="editDeviceInfoDialogForm.yzzSerialNumber" placeholder="请输入粤自助注册码"/>
                </el-form-item>-->

            <el-form-item label="设备经纬度" prop="deploymentCoordinate">
              <el-input v-model="editDeviceInfoDialogForm.deploymentCoordinate" placeholder="请输入设备经纬度"/>
            </el-form-item>

            <el-form-item label="设备IP地址" prop="ipAddress">
              <el-input v-model="editDeviceInfoDialogForm.ipAddress" placeholder="请输入设备IP地址"/>
            </el-form-item>

            <el-form-item label="设备状态" prop="deviceStatus" v-if="editDeviceInfoDialogForm.id">
              <el-select
                v-model="editDeviceInfoDialogForm.deviceStatus"
                placeholder="设备状态"
                clearable
                class="custom-input-width"
              >
                <el-option
                  v-for="dict in dict.type.device_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="运维负责人" prop="operationUserCode">
              <el-select
                v-model="editDeviceInfoDialogForm.operationUserCode"
                placeholder="请选择运维负责人姓名"
                clearable
                filterable
                class="custom-input-width"
              >
                <el-option
                  v-for="item in operationUserOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="设备详细地址" prop="deploymentAddress">
              <el-input v-model="editDeviceInfoDialogForm.deploymentAddress" type="textarea" placeholder="请输入设备详细地址信息"/>
            </el-form-item>

          </el-col>
        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="editDeviceDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设备模块信息 -->
    <el-dialog
      title="设备模块信息"
      :visible.sync="deviceModulesDialogVisible"
      width="1200px"
      append-to-body
    >
      <model-info
        v-loading="deviceModulesDialogLoading"
        :list="deviceModulesListData"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="deviceModulesDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listManager,
  getManager,
  getModelListByDeviceId,
  delManager,
  addManager,
  updateManager
} from "@/api/device/placeManager";
import MyTreeSelectorQuery from "@/views/components/myTreeSelectorQuery";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {checkPermi} from '@/utils/permission'
import ModelInfo from "@/views/device/placeManager/components/modelInfo";
import DeviceDetailInfo from "@/views/device/placeManager/components/deviceDetailInfo";
import {listGroup} from "@/api/device/group";
import {handleTree} from "@/utils/ruoyi";

export default {
  name: "PlaceManager",
  components: {DeviceDetailInfo, ModelInfo, Treeselect, MyTreeSelectorQuery},
  dicts: ['device_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 设备模块弹窗loading遮罩层
      deviceModulesDialogLoading: true,
      // 设备详细信息弹窗loading遮罩层
      deviceDetailDialogLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 是否显示设备详细信息弹出层
      deviceDetailDialogVisible: false,
      // 是否显示添加或修改设备信息弹出层
      editDeviceDialogVisible: false,
      // 是否设备模块信息弹出层
      deviceModulesDialogVisible: false,
      // 设备部署信息详情表单参数
      deviceDetailInfoForm: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupId: undefined,
        deploymentName: undefined, // 部署名称
        deviceId: undefined, // 设备ID
        operationUserName: undefined, // 运维人员
        deviceStatus: undefined, // 设备状态
        regionId: undefined, // 设备所在城市
        deviceName: undefined, // 设备型号
        branchCode: undefined // 默认网点
      },
      // 修改或添加弹窗标题
      editDeviceInfoDialogTitle: "",
      // 修改或添加设备部署信息表单校验
      editDeviceInfoDialogRules: {
        deviceId: [
          {required: true, message: "设备ID不能为空", trigger: "blur"}
        ],
        deploymentName: [
          {required: true, message: "设备部署名称不能为空", trigger: "blur"}
        ],
        productionDate: [
          {required: true, message: "设备生产日期不能为空", trigger: "blur"}
        ],
        deviceCode: [
          {required: true, message: "设备型号不能为空", trigger: "change"}
        ],
        deviceSn: [
          {required: true, message: "设备序列号不能为空", trigger: "blur"}
        ],
        ancestors: [
          {required: true, message: "设备部署区域不能为空", trigger: "change"}
        ],
        deviceStatus: [
          {required: true, message: "设备状态不能为空", trigger: "change"}
        ],
        operationUserCode: [
          {required: true, message: "运维负责人不能为空", trigger: "blur"}
        ],
        groupId: [
          {required: true, message: "设备分组不能为空", trigger: "blur"}
        ],
      },
      // 修改或添加设备部署信息表单内容
      editDeviceInfoDialogForm: {
        id: null,
        deploymentName: "", //设备型号
        regionId: "", //部署城市id
        ancestors: [], //部署城市id数组
        ancestorsName: "", //部署城市中文
        deploymentAddress: "", //详细地址
        deploymentCoordinate: "", //设备经纬度
        ipAddress: "", //设备IP
        deviceId: "", //设备ID
        deviceName: "", //设备型号-bom编码
        deviceCode: "", //设备型号编码
        deviceSn: "", //序列号
        productionDate: "", //生成日期
        /* yzzDeviceCode: "", //粤自助设备编号
         yzzSerialNumber: "", //粤自助注册码*/
        operationUserCode: "", //运维人员编码
        operationUserName: "", //运维人员姓名
        deviceStatus: "2", //设备状态 对应字典查看系统管理字典管理
        groupId: null, //分组id
        branchCode: null, //分组id
        groupName: "", //分组名称
        groupAncestors: "", //分组祖级id
      },
      // 设备模块数据
      deviceModulesListData: [],
      // 分组搜索关键字
      groupFilterKeyword: '',
      // 页面区域选项数据，区域联动选择器和树形选项选择器根据这个数据渲染
      pageRegionDataOptions: [],
      // 区域级联选择器配置
      elCascaderProps: {
        value: 'id',
        label: 'name',
        lazy: true,
        lazyLoad() {
        },
        checkStrictly: true,
        expandTrigger: 'hover'
      },
      // 筛选条件分组选项
      filterGroupOptions: [],
      addDeviceGroupOptions: [],
    };
  },
  computed: {
    //默认显示省份ID
    provinceIdConfig() {
      return this.$store.state.app.provinceIdConfig
    },
    // 网点树形数据
    branchDataOptions() {
      return this.$store.state.device.branchDataOptions || []
    },
    // 所有地区树形数据
    regionDataOptions() {
      return this.$store.state.device.regionDataOptions || []
    },
    // 设备型号下拉框数据
    deviceTypeAndBomCodeOptions() {
      return this.$store.state.device.deviceTypeAndBomCodeOptions || []
    },
    // 运维人员下拉框数据
    operationUserOptions() {
      return this.$store.state.device.operationUserOptions || []
    },
    // 是否有查看设备管理页面权限
    hasDeviceInfoPermission() {
      return checkPermi(['device:device:list']);
    },
    // 是否有查看运维人员信息页面权限
    hasOperationUserPermission() {
      return checkPermi(['device:operationUser:list']);
    },
    // 是否有查看故障日志页面权限
    hasFaultPermission() {
      return checkPermi(['monitor:faultlog:list']);
    },
    // 是否有查看故障日志页面权限
    hasStatusPermission() {
      return checkPermi(['monitor:status:list']);
    },
    // 是否显示表格前面勾选框（具有删除或修改权限才显示）
    showSelection() {
      return checkPermi(['device:placeManager:edit', 'device:placeManager:remove'])
    }
  },
  watch: {
    groupFilterKeyword(newValue) {
      this.$refs.tree.filter(newValue);
    },
    regionDataOptions: {
      handler(newValue) {
        this.pageRegionDataOptions = newValue.map(item => {
          return {
            ...item,
            children: item.children ? null : undefined,
            leaf: item.children ? false : true,
          }
        })
      },
      immediate: true
    }
  },
  created() {
    // 加载设备型号保存到vuex
    this.$store.dispatch('LoadDeviceTypeAndBomCodeOption');

    this.queryParams.regionId = this.provinceIdConfig;

    // 获取分组
    this.getRegionGroup(this.provinceIdConfig, 'filterGroupOptions');

    // 区域联动级联选择器懒加载方法设置
    this.elCascaderProps.lazyLoad = ((node, resolve) => {
      // 如果不是第一级区域或者已经存在子区域了，表示已有子节点不需要重新加载，直接resolve()
      if (node.level !== 1 || node.children.length) return resolve();
      node.data.children = this.regionDataOptions.find(item => {
        return item.id === node.value
      }).children;
      resolve();
    })
  },
  mounted() {
    /*在页面渲染完后调用提前渲染dialog里面内容，解决第一次打开弹窗时，由于里面级联选择器数据过多导致的弹出延迟问题*/
    setTimeout(() => {
      this.$refs.editDeviceInfoDialog.rendered = true;
    }, 500);
  },
  methods: {
    // 加载区域下面子区域选项
    loadRegionOptions({parentNode, callback}) {
      if (parentNode.children && parentNode.children.length) return callback && callback();
      parentNode.children = this.regionDataOptions.find(item => {
        return item.id === parentNode.id
      }).children;
      callback && callback();
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    /** 查询区域包含的分组管理列表 */
    getRegionGroup(regionId, dataName) {
      if (!regionId) return this[dataName] = [];
      const loadingInstance = this.$loading({
        lock: true,
        text: "加载分组中···",
      });
      listGroup({regionId}).then(res => {
        this[dataName] = handleTree(res.rows, "id");
      }).finally(() => {
        loadingInstance.close();
      });
    },
    handleNodeClick(data) {
      this.queryParams.regionId = data.id;
      // 清空选择的分组
      this.queryParams.groupId = null;
      this.getRegionGroup(data.id, 'filterGroupOptions')
      this.handleQuery();
    },
    // 部门树形选择选择时触发
    handleGroupChange(value) {
      this.editDeviceInfoDialogForm.groupName = value.name;
    },
    // 跳转到设备页面
    navToDeviceInfo(deviceCode, needCloseDialog) {
      if (!this.hasDeviceInfoPermission) return;
      if (needCloseDialog) this.deviceDetailDialogVisible = false;
      this.$router.push({
        path: '/device/deviceInfo',
        query: {deviceCode}
      })
    },
    // 跳转到运维人员页面
    navToOperation(operationUserName) {
      if (!this.hasOperationUserPermission) return;
      this.deviceDetailDialogVisible = false;
      this.$router.push({
        name: 'Operation',
        query: {operationUserName}
      })
    },
    // 跳转到心跳日志页面
    navToDeviceStatusLog(deviceStatus, deviceId, needCloseDialog) {
      if (deviceStatus == 2) {
        if (!this.hasStatusPermission) return;
        //  如果设备离线,跳转到心跳日志页面，携带设备ID
        this.$router.push({name: 'DeviceStatusLog', query: {deviceId}})
      } else if (deviceStatus == 3) {
        if (!this.hasFaultPermission) return;
        // 如果设备异常,跳转到故障日志页面，携带设备ID
        this.$router.push({name: 'FaultLog', query: {deviceId}})
      }
      if (needCloseDialog) this.deviceDetailDialogVisible = false;
    },

    // 查看设备模块
    handleViewDeviceModules(row) {
      // 清空之前数据
      this.deviceModulesListData = [];
      this.deviceModulesDialogVisible = true;
      this.getModelList(row.deviceId);
    },

    /*根据id查找祖级id
    @params { Array } sourceData 要查找的数据源
    @params { Number/String } id 查找的id
    @params { Boolean } includeSelf 返回值是否包含自己id
    @return { String } id 祖级id拼接","字符串
    */
    findAncestorsId(sourceData, id, includeSelf = false) {
      const find = (array, id) => {
        //储存父级id
        let stack = [];
        //是否继续循环
        let going = true;

        let walker = (array, id) => {
          array.forEach(item => {
            if (!going) return;
            stack.push(item['id']);
            if (item['id'] == id) {
              going = false;
            } else if (item['children']) {
              walker(item['children'], id);
            } else {
              stack.pop();
            }
          });
          if (going) stack.pop();
        }

        walker(array, id);

        // 返回包含自身id的拼接字符串
        if (includeSelf) return stack.join(',');

        // 去掉自身id的拼接字符串
        return stack.slice(0, stack.length - 1).join(',');
      }
      return find(sourceData, id);
    },

    /** 转换分组树形图数据结构 */
    branchNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.branchCode,
        label: node.branchName,
        children: node.children || undefined,
      };
    },

    /** 转换树形图数据结构 */
    treeNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },

    /*查找下拉框选中项label
      @param {Array} originData 下拉框选项数据
      @param {String} valueName 下拉框的value绑定在editDeviceInfoDialogForm的参数名
      @return {Object} 下拉框选中项的文本
     */
    findSelectorItem(originData, valueName) {
      return originData.find(item => {
        return this.editDeviceInfoDialogForm[valueName] === item.value
      }).label
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs.editDeviceInfoForm.validate((valid) => {
        // console.log("Before提交表单=====>",  this.editDeviceInfoDialogForm)
        if (valid) {
          // 获取地址级联选择器选中城市的中文拼接起来
          const ancestorsName = this.$refs.cascader.getCheckedNodes()[0].pathLabels.join('');
          // 获取运维人员下拉框选中的文本
          const operationUserName = this.findSelectorItem(this.operationUserOptions, 'operationUserCode')
          // 根据设备编码获取设备型号,
          const device = this.deviceTypeAndBomCodeOptions.find(item => {
            return item.value === this.editDeviceInfoDialogForm.deviceCode
          });
          // 如果修改时设备型号已被删除的话直接使用原来的deviceName
          const deviceName = device ? device.name : this.editDeviceInfoDialogForm.deviceName;

          // 将选中部署区域的祖级id前面统一加0，方便后端查询
          let ancestors = [0, ...this.editDeviceInfoDialogForm.ancestors.slice(0, -1)].join(",");

          // 最后一级的区域id
          const regionId = this.editDeviceInfoDialogForm.ancestors[this.editDeviceInfoDialogForm.ancestors.length - 1];
          //分组祖级id拼接字符串
          const groupAncestors = this.findAncestorsId(this.addDeviceGroupOptions, this.editDeviceInfoDialogForm.groupId);

          const params = {
            id: this.editDeviceInfoDialogForm.id,
            deviceId: this.editDeviceInfoDialogForm.deviceId,
            deploymentName: this.editDeviceInfoDialogForm.deploymentName,
            regionId,
            ancestors,
            ancestorsName,
            deploymentAddress: this.editDeviceInfoDialogForm.deploymentAddress,
            ipAddress: this.editDeviceInfoDialogForm.ipAddress,
            deviceCode: this.editDeviceInfoDialogForm.deviceCode, //设备型号编码
            deviceName,
            deviceSn: this.editDeviceInfoDialogForm.deviceSn,
            productionDate: this.editDeviceInfoDialogForm.productionDate,
            /* yzzDeviceCode: this.editDeviceInfoDialogForm.yzzDeviceCode,
             yzzSerialNumber: this.editDeviceInfoDialogForm.yzzSerialNumber,*/
            operationUserCode: this.editDeviceInfoDialogForm.operationUserCode,
            operationUserName,
            deviceStatus: this.editDeviceInfoDialogForm.deviceStatus,
            deploymentCoordinate: this.editDeviceInfoDialogForm.deploymentCoordinate,
            groupId: this.editDeviceInfoDialogForm.groupId, //分组id
            branchCode: this.editDeviceInfoDialogForm.branchCode || null, //默认网点id
            groupName: this.editDeviceInfoDialogForm.groupName, //分组名称
            groupAncestors: groupAncestors,
          }

          // console.log(params, "请求参数");
          if (this.editDeviceInfoDialogForm.id !== null) {
            updateManager(params).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.editDeviceDialogVisible = false;
              this.getList();
              this.$store.dispatch("LoadPlaceManagerOptions");
            })

            // console.log("修改设备信息", this.editDeviceInfoDialogForm)

          } else {
            addManager(
              params
            ).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.editDeviceDialogVisible = false;
              this.getList();
              this.$store.dispatch("LoadPlaceManagerOptions");
            })
            // console.log("新增设备信息", params)
          }

        } else {
          return false;
        }
      });
    },

    /** 查询设备部署管理列表 */
    getList() {
      this.loading = true;
      // 复制请求参数
      const params = {...this.queryParams};

      listManager(params).then(response => {
          // 是否已经加载过设备列表标记改为true
          if (!this.alreadyGetList) this.alreadyGetList = true;
          this.list = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },

    /** 查询设备模块列表 */
    getModelList(deviceId) {
      this.deviceModulesDialogLoading = true;
      getModelListByDeviceId({deviceId}).then(response => {
          this.deviceModulesListData = response.rows;
          this.deviceModulesDialogLoading = false;
        }
      )
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // console.log("查询参数", this.queryParams)
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.deviceCode = null;
      this.queryParams.operationUserName = null;
      this.handleQuery();
    },

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    /** 详细按钮操作 */
    handleView(row) {
      this.deviceDetailDialogVisible = true;
      this.deviceDetailDialogLoading = true;
      const id = row.id;
      getManager(id).then(response => {
        this.deviceDetailInfoForm = response.data;
        this.deviceDetailDialogLoading = false;
      });
    },

    // 重置表单值
    reset() {
      // 重置表单信息
      this.editDeviceInfoDialogForm = {
        id: null,
        deploymentName: "",
        regionId: "",
        ancestors: [],
        ancestorsName: "",
        deploymentAddress: "",
        deploymentCoordinate: "",
        ipAddress: "",
        deviceId: "",
        deviceCode: "", //设备型号编码
        deviceName: "",
        deviceSn: "",
        productionDate: "",
        /*yzzDeviceCode: "",
        yzzSerialNumber: "",*/
        operationUserCode: "",
        operationUserName: "",
        deviceStatus: "2",
        groupId: null, //分组id
        branchCode: null, //默认网点
        groupName: "", //分组名称
        groupAncestors: ""
      };
      // 表单重置为初始值并移除校验结果
      this.resetForm("editDeviceInfoForm");
      this.addDeviceGroupOptions = [];
    },

    /** 新增按钮操作 */
    handleAdd() {
      //表单重置为初始值并移除校验结果
      this.reset();
      this.editDeviceDialogVisible = true;
      this.editDeviceInfoDialogTitle = "添加设备部署信息";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      //表单重置为初始值并移除校验结果
      this.reset();
      const id = row.id || this.ids;
      getManager(id).then(response => {
        const deviceInfoDialogForm = response.data;
        // 获取分组选项
        this.getRegionGroup(deviceInfoDialogForm.regionId, 'addDeviceGroupOptions')

        /*把ancestors字符串转为数组,因为在添加的时候统一给ancestors加了父级id0，并且去掉了自身id
          在更新的时候要将最第一级0去掉,在最后面加上自身id */
        deviceInfoDialogForm.ancestors = deviceInfoDialogForm.ancestors.split(",").slice(1);
        deviceInfoDialogForm.ancestors.push(deviceInfoDialogForm.regionId);

        const parentNode = this.pageRegionDataOptions.find(item => {
          return item.id === deviceInfoDialogForm.ancestors[0]
        }) || {}


        // 如果该省份不存在子区域数据并且不是最后一级，需要提前添加数据渲染，才能让修改时自动选中区域
        if (!parentNode.children && !parentNode.leaf) {
          this.loadRegionOptions({parentNode})
        }

        this.editDeviceInfoDialogForm = deviceInfoDialogForm;

        this.editDeviceDialogVisible = true;
        this.editDeviceInfoDialogTitle = "修改设备部署信息";
      });

    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const operIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的设备？').then(function () {
      }).then(() => {
        delManager(operIds).then(response => {
          this.$modal.msgSuccess("删除设备成功！");
          this.$store.dispatch("LoadPlaceManagerOptions");
          this.getList();
        })
      }).catch(() => {
      });
    },

    /** 导出按钮操作 */
    handleExport() { // 获取当前时间做为导出文件名
      const currentDate = this.parseTime(new Date());

      this.download('device/placeManager/export', {
        ...this.queryParams
      }, `设备部署管理_${currentDate}.xlsx`)
    },

  },
  beforeRouteEnter(to, from, next) {
    const {deviceCode, operationUserName} = to.query;
    // 如果存在跳转参数deviceCode,自动填入查询条件
    if (deviceCode || operationUserName) {
      next(vm => {
        vm.resetForm("queryForm");
        vm.queryParams.deviceCode = deviceCode;
        vm.queryParams.operationUserName = operationUserName;
        vm.getList();
      })
    } else {
      // 不存在查询参数
      next(vm => {
        // 判断是否已经加载过列表了，当还没有加载过列表时才调用获取列表接口
        if (!vm.alreadyGetList) {
          vm.getList();
        }
      });
    }
  },
  beforeRouteLeave(to, from, next) {
    if (this.deviceDetailDialogVisible) this.deviceDetailDialogVisible = false;
    next();
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  min-height: inherit;

  .right-wrap {
    flex: 1;
    width: 100%;
    height: 100%;
    overflow: hidden;
  }

  .group-wrap {
    box-sizing: border-box;
    width: 240px;
    height: inherit;
    min-width: 250px;
    margin-left: -5px;
    padding: 10px;
    margin-right: 15px;
    border: 1px solid #dfe4ed;
    border-radius: 4px;

    .title {
      margin-bottom: 10px;
      font-size: 14px;
      color: #606266;
      font-weight: bold;
    }

    .tree-wrap {
      width: 100%;
      height: inherit;
      overflow-y: auto;
    }
  }

}

::v-deep .vue-treeselect__control {
  height: 32px;
  width: 215px;
  line-height: 32px !important;
}

.custom-input-width {
  width: 100%;

  ::v-deep .vue-treeselect__control {
    width: 100%;
  }
}

.tag {
  cursor: pointer;
}

.pointer {
  cursor: pointer;
}

::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background: #409eff42;
}
</style>

